package com.tanhua.service;


import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.mongo.Visitor;
import com.tanhua.domain.vo.CommonLikeUserVO;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.*;
import com.tanhua.template.AliyunSmsTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.util.JwtsUtils;
import com.tanhua.util.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class UserService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AliyunSmsTemplate smsTemplate;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Reference
    private UserApi userApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private VisitorsApi visitorsApi;
    @Reference
    private FriendApi friendApi;

    private static final String CODE_PREFIX = "CODE_";
    private static final String TOKEN_PREFIX = "TOKEN_";

    @Value("{key.secret}")
    private String secret;


    public ResponseEntity sendSms(String mobile) {
        //1. 通过发短信的模板工具类发送短信
        // String code = smsTemplate.sendSms(mobile);
        String code = "654321";
        redisTemplate.delete(CODE_PREFIX + mobile);

        //2. 把验证码临时存储起来：存储到redis里
        redisTemplate.opsForValue().set(CODE_PREFIX + mobile, code, Duration.ofMinutes(5));

        //3. 返回结果
        log.info("发送手机验证码，mobile:{}, code:{}", mobile, code);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity loginVerification(String phone, String code) {
        String value = redisTemplate.opsForValue().get(CODE_PREFIX + phone);
        if (value == null || !code.equals(value)) {
            return ResponseEntity.status(500).body(ErrorResult.smsInvalid());
        }
        boolean isNew = false;

        User user = userApi.findByPhone(phone);
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            huanXinTemplate.register(id.toString(), "123456");
            user.setId(id);
            isNew = true;
        }
        //=============记录log==============
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getId());
        map.put("type", isNew?"0102":"0101");
        map.put("logTime", new DateTime().toString("yyyy-MM-dd"));
        rocketMQTemplate.convertAndSend("logTopic",map);
        //=============结束=================

        String token = JwtsUtils.getJwts(phone, user.getId(), secret);
        redisTemplate.opsForValue().set(TOKEN_PREFIX + token, JSON.toJSONString(user));
        HashMap<String, Object> result = new HashMap<>();
        result.put("isNew", isNew);
        result.put("token", token);
        return ResponseEntity.ok(result);
    }


    public ResponseEntity checkVerificationCode(String code) {
        HashMap<String, Boolean> map = new HashMap<>();
        User user = UserHolder.getUser();
        String value = redisTemplate.opsForValue().get(CODE_PREFIX + user.getMobile());
        System.out.println(value);
        if (value == null || !value.equals(code)) {
            map.put("verification", false);
            return ResponseEntity.status(500).body(map);
        }
        map.put("verification", true);
        redisTemplate.delete(CODE_PREFIX + user.getMobile());
        return ResponseEntity.ok(map);
    }

    public ResponseEntity updatePhone(String phone, String token) {

        User user = UserHolder.getUser();
        user.setMobile(phone);
        redisTemplate.opsForValue().set(TOKEN_PREFIX + token, JSON.toJSONString(user));
        System.out.println(user.toString());
        userApi.updatePhone(user);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity counts() {
        User user = UserHolder.getUser();

        int eachLoveCount = userLikeApi.eachLoveCount(user.getId());
        int fanCount = userLikeApi.fanCount(user.getId());
        int loveCount = userLikeApi.loveCount(user.getId());
        HashMap<String, Integer> map = new HashMap<>();
        map.put("eachLoveCount", eachLoveCount);
        map.put("fanCount", fanCount);
        map.put("loveCount", loveCount);

        return ResponseEntity.ok(map);
    }

    public ResponseEntity typeList(Integer type, Integer page, Integer pagesize) {
        User user = UserHolder.getUser();
        ArrayList<CommonLikeUserVO> vos = new ArrayList<>();
        PageResult pageResult = null;
        if (type == 1) {
            pageResult = userLikeApi.findeachLoveList(user.getId(), page, pagesize);
            List<Friend> items = pageResult.getItems();
            for (Friend friend : items) {
                CommonLikeUserVO vo = new CommonLikeUserVO();
                UserInfo userInfo = userInfoApi.findUserInfo(friend.getFriendId());
                BeanUtils.copyProperties(userInfo, vo);
                Integer score = userLikeApi.findScore(friend.getUserId(), friend.getFriendId());
                vo.setMatchRate(score);
                vos.add(vo);
            }

        } else if (type == 2) {
            pageResult = userLikeApi.findLoveList(user.getId(), page, pagesize);
            List<UserLike> items = pageResult.getItems();
            for (UserLike userLike : items) {
                CommonLikeUserVO vo = new CommonLikeUserVO();
                UserInfo userInfo = userInfoApi.findUserInfo(userLike.getLikeUserId());
                BeanUtils.copyProperties(userInfo, vo);
                Integer score = userLikeApi.findScore(userLike.getUserId(), userLike.getLikeUserId());
                vo.setMatchRate(score);
                vos.add(vo);
            }

        } else if (type == 3) {
            pageResult = userLikeApi.findFanList(user.getId(), page, pagesize);
            List<UserLike> items = pageResult.getItems();
            for (UserLike userLike : items) {
                CommonLikeUserVO vo = new CommonLikeUserVO();
                UserInfo userInfo = userInfoApi.findUserInfo(userLike.getUserId());
                BeanUtils.copyProperties(userInfo, vo);
                Integer score = userLikeApi.findScore(userLike.getLikeUserId(), userLike.getUserId());
                vo.setMatchRate(score);
                vos.add(vo);
            }
        } else if (type == 4) {
            pageResult = visitorsApi.findVisitors(user.getId(), page, pagesize);
            List<Visitor> items = pageResult.getItems();
            for (Visitor visitor : items) {
                CommonLikeUserVO vo = new CommonLikeUserVO();
                UserInfo userInfo = userInfoApi.findUserInfo(visitor.getVisitorUserId());
                BeanUtils.copyProperties(userInfo, vo);
                Integer score = userLikeApi.findScore(visitor.getUserId(), visitor.getVisitorUserId());
                vo.setMatchRate(score);
                vos.add(vo);
            }
        }
            pageResult.setItems(vos);
            return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity fansLike(Long fanId) {
        User user = UserHolder.getUser();
        userLikeApi.fansLike(user.getId(),fanId);
        friendApi.add(fanId,user.getId());
        huanXinTemplate.addContact(user.getId().toString(),fanId.toString());

        return ResponseEntity.ok(null);
    }
}
